package com.project.dao.impl;

import com.project.bean.UserBean;
import com.project.dao.IUserDao;

import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl extends BassDao implements IUserDao {
    @Override
    public UserBean login(String username, String pwd) {
        UserBean user=null;
        this.setConnection();
        try {
            ps=con.prepareStatement("SELECT * FROM  t_user WHERE t_name= ?AND t_pwd=?;");
            ps.setObject(1,username);
            ps.setObject(2,pwd);
            rs= ps.executeQuery();
            while (rs.next()){
                user=new UserBean();
                user.setName(rs.getString("t_name"));
                user.setPwd(rs.getString("t_pwd"));
                user.setBirthday(LocalDate.parse(rs.getString("t_birthday")));
                user.setPhone(rs.getString("t_phone"));
                user.setMoney(rs.getInt("t_money"));
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
        return user;
    }

    @Override
    public void add(UserBean userBean) {
        this.setConnection();
        try {
            ps=con.prepareStatement("INSERT  INTO t_user(t_name,t_pwd,t_birthday,t_phone,t_money)\n" +
                    "VALUES(?,?,?,?,?)");

            ps.setObject(1,userBean.getName());
            ps.setObject(2,userBean.getPwd());
            ps.setObject(3,userBean.getBirthday());
            ps.setObject(4,userBean.getPhone());
            ps.setObject(5,userBean.getMoney());
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
    }

    @Override
    public List<UserBean> findAll() {
        List<UserBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps=con.prepareStatement("select *from t_user");
            rs=ps.executeQuery();
            while (rs.next()){
                UserBean user = new UserBean();
                user.setId(rs.getInt("pk_userId"));
                user.setName(rs.getString("t_name"));
                user.setPwd(rs.getString("t_pwd"));
                user.setBirthday(LocalDate.parse(rs.getString("t_birthday")));
                user.setPhone(rs.getString("t_phone"));
                user.setMoney(rs.getInt("t_money"));
                list.add(user);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.closeConnection();
        }
        return list;
    }

}
